package com.gzcstec.yien.controller;

import com.gzcstec.yien.domain.User;
import com.gzcstec.yien.redis.RedisService;
import com.gzcstec.yien.redis.UserKey;
import com.gzcstec.yien.result.MsgCode;
import com.gzcstec.yien.result.Result;
import com.gzcstec.yien.service.UserService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by yien on 2018/3/30.
 */
@Controller
@RequestMapping("/demo")
public class DemoController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisService redisService;

    @RequestMapping("/hello")
    @ResponseBody
    public Result<String> hello() {
        return Result.success("hello world");
    }

    @RequestMapping("/error")
    @ResponseBody
    public Result error() {
        return Result.error(MsgCode.SYSTEM_ERROR);
    }

    @RequestMapping("/thymeleaf")
    public String thymeleaf(Model model) {
        model.addAttribute("name" , "yien");
        return "hello";
    }

    @RequestMapping("/getUserById")
    @ResponseBody
    public Result getUserById(@Param("id")int id) {
        User user =  userService.getById(id);
        return Result.success(user);
    }

    @RequestMapping("/addUserByTx")
    @ResponseBody
    @Transactional
    public Result addUser() {
        User u1 = new User();
        u1.setId(1);
        u1.setName("fan");

        User u2 = new User();
        u2.setId(2);
        u2.setName("xiong");

        userService.addUser(u2);
        userService.addUser(u1);

        return Result.success("success");
    }

    @RequestMapping("/getUserByCache")
    @ResponseBody
    public Result getUserByCache(@Param("id") int id) {

       User user = redisService.get(UserKey.getById , String.valueOf(id) , User.class);
       if(null == user) {
           user = userService.getById(id);
           redisService.set(UserKey.getById , String.valueOf(user.getId()) , user);
       }

       return Result.success(user);
    }

}
